package com.ajiao5.blob;

import com.bean.Customer;
import com.util.JDBCUtil;
import org.junit.Test;

import javax.lang.model.element.VariableElement;
import java.io.*;
import java.sql.*;

/**
 * 使用prepareStatement操作blob类型的数据
 */
public class BlobTest {
    //向数据表customers中插入Blob类型的字段
    @Test
    public void testInsert() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        String sql = "insert into customers(name,email,birth,photo)values(?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setObject(1, "张子豪");
        ps.setObject(2, "9564134.com");
        ps.setObject(3, "1992-09-04");
        FileInputStream inputStream = new FileInputStream(new File("src/com/ajiao5/blob/姜泰莉4k壁纸3840x2160_彼岸图网.jpg"));

        ps.setBlob(4, inputStream);
        ps.execute();
        JDBCUtil.CloseResource(conn, ps);
    }

    //查询数据表中的blob类型字段
    @Test
    public void testQuery() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        FileOutputStream fos = null;
        InputStream stream = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select id,name,email,birth,photo from customers where id=?";
            ps = conn.prepareStatement(sql);
            //填充占位符
            ps.setInt(1, 20);
            //结果集
            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");
                Date date = resultSet.getDate("birth");

                Customer customer = new Customer(id, name, email, date);
                System.out.println(customer);

                //将blob类型的字段下载下来，以文件的方式保存在本地
                Blob photo = resultSet.getBlob("photo");

                //二进制流
                stream = photo.getBinaryStream();

                fos = new FileOutputStream("xiexie.jpg");
                byte[] buffer = new byte[1024];
                int len;
                while ((len = stream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        JDBCUtil.CloseResource(conn, ps, resultSet);

    }
}
